package org.origin.centre.filter;

import org.origin.centre.support.utils.BasicUtil;
import org.origin.centre.support.utils.TraceUtil;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * xss攻击，cros恶意访问过滤器，需要添加注解 @Configuration @WebFilter
 *
 * @author ferret
 * @version 2024-05-08
 */
@SuppressWarnings("unused")
@WebFilter(filterName = "headerEnhanceFilter", urlPatterns = "/*", asyncSupported = true)
public class XssHeaderEnhanceFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            String requestNo = req.getHeader(TraceUtil.RequestNoKey);
            HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);
            if (BasicUtil.isBlank(requestNo)) {
                requestNo = BasicUtil.uuid();
            }
            TraceUtil.addTrace(requestNo);
            requestWrapper.addHeader(TraceUtil.RequestNoKey, requestNo);
            chain.doFilter(requestWrapper, response);
        } finally {
            TraceUtil.delTrace();
        }
    }

}
